<template>
  <div>
    <el-card>
      <!-- 用于选择excel文件 -->
      <input type="file" ref="excelFileInput" accept=".xlsx,.xls" style="display: none;" @change="handleFileUpload">
      <!-- 筛选区域 -->
      <el-row :gutter="20" type="flex" justify="start" align="items: center">
        <el-col :span="7">
          <el-input v-model="searchTerm" placeholder="请输入设备名称" clearable @keyup.enter="getDeviceInfoByName"></el-input>
        </el-col>
        <el-col :span="8">
          <el-button id="filter-button" type="primary" @click="getDeviceInfoByName">查询</el-button>
          <el-button id="reset-button" type="default" @click="resetFilter">重置</el-button>
          <!-- 添加设备按钮 -->
          <el-button type="primary" style="width: 8vw;" @click="openDialog">添加设备</el-button>
          <!-- excel导入按钮 -->
          <el-button type="primary" style="width: 8vw;" @click="importFromExcel">Excel 导入</el-button>
        </el-col>
      </el-row>
      <!-- 列表区 -->
      <div style="height: 64vh;">
        <el-skeleton :loading="loading" animated>
          <el-table :data="paginatedData" border height="100%" style="width: 100%; margin-top:20px">
            <el-table-column type="index" label="序号" width="50">
              <!-- 索引自动标号 -->
              <template #default="scope">
                {{ getSequentialNumber(scope.$index) }}
              </template>
            </el-table-column>
            <el-table-column prop="deviceNo" label="设备编号" min-width="60"/>
            <el-table-column prop="deviceName" label="设备名称" min-width="70" />
            <el-table-column prop="deviceModel" label="设备型号" width="170" />
            <!-- <el-table-column prop="deviceNo" label="设备物料编码" width="145" /> -->
            <el-table-column prop="deviceGrade" label="设备等级" min-width="40" />
            <el-table-column prop="counts" label="数量" min-width="30" />
            <el-table-column prop="manufacture" label="制造商" min-width="100"/>
            <el-table-column prop="serviceLife" label="设备使用寿命" min-width="30" />
            <el-table-column label="操作" min-width="80">
              <template #default="scope">
                
                <el-button type="primary" @click="editDevice(scope.row.deviceNo)">编辑</el-button>
                <el-button id="delete-button" type="default" @click="deleteDeviceInfo(scope.row.deviceNo)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>
      <!-- 分页 -->
      <template #footer>
        <div style="margin-top: -30px">
          <Pagination
            :total="total"
            :current-page="searchForm.current"
            @update:current-page="val => searchForm.current = val"
            :total-pages="totalPages" 
          />
        </div>
      </template>
    </el-card>

    <!-- 添加设备信息的弹出窗口 -->
    <el-dialog title="添加设备信息" v-model="dialogVisible" width="40%">
      <el-form :model="newDeviceInfo" label-width="100px">
        <el-form-item label="设备名称:">
          <el-input v-model="newDeviceInfo.deviceName"></el-input>
        </el-form-item>
        <el-form-item label="设备编号:">
          <el-input v-model="newDeviceInfo.deviceNo"></el-input>
        </el-form-item>
        <el-form-item label="设备型号:">
          <el-input v-model="newDeviceInfo.deviceModel"></el-input>
        </el-form-item>
        <el-form-item label="设备等级:">
          <el-input v-model="newDeviceInfo.deviceGrade"></el-input>
        </el-form-item>
        <el-form-item label="数量:">
          <el-input v-model="newDeviceInfo.counts"></el-input>
        </el-form-item>
        <el-form-item label="制造商:">
          <el-input v-model="newDeviceInfo.manufacture"></el-input>
        </el-form-item>
        <el-form-item label="设备使用寿命:">
          <el-input v-model="newDeviceInfo.serviceLife"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addDeviceInfo">添加</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑设备信息弹窗 -->
    <el-dialog title="编辑设备信息" v-model="editDialogVisible" width="35%">
      <el-form :model="editDeviceInfo" label-width="96px">
        <el-form-item label="设备名称">
          <el-input v-model="editDeviceInfo.deviceName"></el-input>
        </el-form-item>
        <el-form-item label="设备编号:">
          <el-input v-model="editDeviceInfo.deviceNo" readonly></el-input>
        </el-form-item>
        <el-form-item label="设备型号:">
          <el-input v-model="editDeviceInfo.deviceModel"></el-input>
        </el-form-item>
        <el-form-item label="设备等级:">
          <el-input v-model="editDeviceInfo.deviceGrade"></el-input>
        </el-form-item>
        <el-form-item label="数量:">
          <el-input v-model="editDeviceInfo.counts"></el-input>
        </el-form-item>
        <el-form-item label="制造商:">
          <el-input v-model="editDeviceInfo.manufacture"></el-input>
        </el-form-item>
        <el-form-item label="设备使用寿命:">
          <el-input v-model="editDeviceInfo.serviceLife"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateDevice">更新</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import Pagination from '@/components/Table/Pagination';
import { ElMessage,ElMessageBox} from 'element-plus';
import dmApi from '@/api/deviceInfoManage';

const searchTerm = ref('');
const dialogVisible = ref(false);
const editDialogVisible = ref(false);
//表单
const newDeviceInfo = reactive({
  deviceName: '',
  deviceNo: '',
  deviceModel: '',
  deviceGrade: '',
  counts: '',
  manufacture: '',
  serviceLife: ''
});

//编辑输入框
const editDeviceInfo = reactive({
  deviceName: '',
  deviceNo: '',
  deviceModel: '',
  deviceGrade: '',
  counts: '',
  manufacture: '',
  serviceLife: ''
});

const router = useRouter();

onMounted(() => {
  getDeviceInfo();
});

const allTableData = ref([]);
const tableData = ref([]);
const total = computed(() => tableData.value.length);
const totalPages = ref(1);

watch(allTableData, (newData) => {
  tableData.value = [...newData];
});

watch(total, (newData) => {
  totalPages.value = Math.ceil(newData / searchForm.size);
});

const handlePageChange = (page) => {
  searchForm.current = page;
};

const searchForm = reactive({
  current: 1,
  size: 10
});

// 新增计算属性来生成连续的序号
const getSequentialNumber = (index) => {
  return (searchForm.current - 1) * searchForm.size + index + 1;
};

// 获取设备信息列表
const getDeviceInfo = async () => {
  try {
    const res = await dmApi.getDeviceInfo(null);
    if (res.data.status) {
      allTableData.value = res.data.data;
    } else {
      ElMessage.error('获取后端数据失败');
      console.log(res.data.message);
    }
  } catch (error) {
    ElMessage.error('获取设备信息失败');
    console.log(error);
  }
};

const paginatedData = computed(() => {
  const start = (searchForm.current - 1) * searchForm.size;
  const end = start + searchForm.size;
  return tableData.value.slice(start, end);
});

// 根据设备名称模糊查询设备信息
const getDeviceInfoByName = async () => {
    if (searchTerm.value.trim()!== '') {
        try {
            const res = await dmApi.getDeviceInfoByName(searchTerm.value);
            if (res.status) {
                tableData.value = res.data;
            } else {
                ElMessage.error('获取后端数据失败');
                console.log(res.data.status);
            }
        } catch (error) {
            ElMessage.error('获取设备信息失败');
            console.log(error);
        }
    } else {
        getDeviceInfo();
    }
};

// 重置
const resetFilter = () => {
  searchTerm.value = '';
  tableData.value = [...allTableData.value];
};

// 打开添加设备信息的弹窗
const openDialog = () => {
  dialogVisible.value = true;
};

// 添加设备信息
const addDeviceInfo = async () => {
  try {
    const res = await dmApi.addDeviceInfo(newDeviceInfo);
    // console.log(res);
    if (res.data.status) {
      ElMessage.success('设备信息添加成功');
      dialogVisible.value = false;
      Object.assign(newDeviceInfo, {
      deviceName: '',
      deviceNo: '',
      deviceModel: '',
      deviceGrade: '',
      counts: '',
      manufacture: '',
      serviceLife: ''
      });
      getDeviceInfo();
    } else {
      ElMessage.error(res.data.msg);
      Object.assign(newDeviceInfo, {
      deviceName: '',
      deviceNo: '',
      deviceModel: '',
      deviceGrade: '',
      counts: '',
      manufacture: '',
      serviceLife: ''
      });
      getDeviceInfo();
    } 
  } catch (error) {
    ElMessage.error('设备信息添加失败');
    console.log(error);
  }
};

// 删除设备信息
// const deleteDeviceInfo = async (deviceNo) => {
//   try {
//     await dmApi.deleteDeviceInfoByNo(deviceNo);
//     ElMessage.success('设备信息删除成功');
//     getDeviceInfo();
//     // location.reload();
//   } catch (error) {
//     ElMessage.error('设备信息删除失败');
//     console.log(error);
//   }
// };
const deleteDeviceInfo = async (deviceNo) => {
       console.log('Before confirm');
       await ElMessageBox.confirm("此操作将永久删除该设备信息, 是否继续?", "提示", {
           confirmButtonText: "确定",
           cancelButtonText: "取消",
           type: "warning"
       }).then(async () => {
           console.log('Confirm clicked');
           try {
               await dmApi.deleteDeviceInfoByNo(deviceNo);
               ElMessage.success('设备信息删除成功');
               getDeviceInfo();
           } catch (error) {
               ElMessage.error('设备信息删除失败');
               console.log(error);
           }
       }).catch(() => {
           console.log('Cancel clicked');
           ElMessage.info("已取消删除");
       });
       console.log('After confirm');
   };

// 打开编辑设备信息窗口
const editDevice = (deviceNo) => {
  const device = allTableData.value.find(item => item.deviceNo === deviceNo);
  if (device) {
    Object.assign(editDeviceInfo, device);
    editDialogVisible.value = true;
  } else {
    ElMessage.error('未找到设备信息');
  }
};

// 编辑设备信息弹窗
const updateDevice = async () => {
  try {
    const res = await dmApi.updateDeviceInfo(editDeviceInfo);
    // console.log(res);
    if (res.data.status) {
      ElMessage.success('设备信息更新成功');
      editDialogVisible.value = false;
      getDeviceInfo();
    } else {
      ElMessage.error(res.data.msg);
      ElMessage.error('请检查修改的信息格式是否正确');
    }
  } catch (error) {
    ElMessage.error('设备信息更新失败');
    console.log(error);
  }
};

//触发excel文件选择对话框。
const importFromExcel = () => {
    // 触发文件选择对话框
    document.querySelector('input[type=file]').click();
};

// 处理excel文件选择后的操作
const handleFileUpload = (event) => {
  //从事件对象event中获取用户选择的文件
  //event.target.files是一个文件列表，[0]表示获取列表中的第一个文件
  const file = event.target.files[0];
  if (file) {
    const formData = new FormData ();
    //将获取到的文件添加到FormData对象中
    //指定了一个键excelFile，这个键在后端接收文件时会用到，用于识别上传的文件
    formData.append ('excelFile', file);
    // 调用后端接口上传文件
    //.then(response => {...})是一个 Promise 的成功处理程序，当后端成功响应请求并返回数据时，会执行这个函数
    dmApi.importExcel (formData).then (response => {
      console.log(response);
      if (response.data.status) {
        ElMessage.success (' 设备信息导入成功 ');
        getDeviceInfo ();
      } else {
        ElMessage.error (' 设备信息导入失败--' + response.data.message + '--导入的数据可能已存在');
      }
    }).catch (error => {
        ElMessage.error (' 文件上传出错 ');
        console.log (error);
      });
  }
};

//加载loading页面
const loading = ref(true);
watch(
    () => paginatedData.value,
    (newValue) => {
      loading.value = !(newValue && newValue.length > 0);
    },
    //配置项确保在组件挂载时，立即执行一次回调，以根据初始值正确设置 loading 的状态
    { immediate: true } // 立即执行一次，以确保初始值状态正确
);

</script>

<style scoped lang="scss">
/*筛选-重置按钮*/
.el-button {
    @include button-style;
}

/*card背景、边框*/
.el-card {
  width: 100%;
  background-color: transparent;
  --el-card-border-color: transparent;
}
/*数据表背景*/
:deep(.el-table) {
  color: $color-font-table;//字体颜色
  background-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: transparent;
  --el-table-row-hover-bg-color: transparent;

  // 鼠标悬停时的行样式
  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        color: $color-font-table-hover; // 悬停时字体颜色
      }
    }
  }
}

:deep(.el-card__body){
    padding:0 0 10px 0px;
}

  /*日期筛选框背景*/
:deep([data-v-6594cc13] .el-input__wrapper) {
    background-color: #000C34;
}

  :deep(.el-input__inner) {
      color: white;
}

#delete-button,
#reset-button {
  @include reset-style
}


//对话框
:deep(.el-dialog) {
  background-color: #14255f;
  width: 30vw;
}
:deep(.el-dialog__title) {
    color: white;

}

:deep(.el-form-item__label ) {
    color: white;
        text-align: right;
}
//
</style>